package com.example.crm_system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.crm_system.config.JwtInterceptor;
import com.example.crm_system.config.Result;
import com.example.crm_system.entity.*;
import com.example.crm_system.exception.MyOwnException;
import com.example.crm_system.mapper.CustomerMapper;
import com.example.crm_system.service.CustomerService;
import com.github.pagehelper.*;
import jakarta.annotation.Resource;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerMapper customerMapper;

    // 插入customer
    @PostMapping("/insert")
    public Result insert(@RequestBody Customer customer) {
        if (customer.getCno() == null) {
            customerService.insert(customer);
        } else {
            customerService.update(customer);
        }
        return Result.success();
    }

    // 删除customer
    @DeleteMapping("/delete/{cno}")
    public Result delete(@PathVariable Integer cno) {
        customerService.delete(cno);
        return Result.success();
    }

    // 查询所有customer
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Customer> list =  customerService.selectAll();
        return Result.success(list);
    }

    // 通过cno查询customer
    @GetMapping("/selectByCno/{cno}")
    public Result selectByCno(@PathVariable Integer cno) {
        List<Customer> list = customerService.selectByCno(cno);
        return Result.success(list);
    }

    // 查询方法
    @GetMapping("/searchCustomer")
    public Result searchCustomer(Params params) {
        PageInfo<Customer> list = customerService.searchCustomer(params);
        return Result.success(list);
    }

    // 导出Excel
    @GetMapping("/export")
    public void export(HttpServletResponse response, Params params) throws IOException {
        try {
            List<Customer> all;
            if (params != null && (params.getCname() != null || params.getPhone() != null)) {
                // 有查询条件时，使用带条件的查询
                all = customerMapper.searchCustomer(params);
            } else {
                // 无查询条件时，获取所有数据
                all = customerService.findAll();
            }

            if (CollectionUtil.isEmpty(all)) {
                // 返回空Excel而不是抛出异常
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment;filename=empty.xlsx");
                try (ServletOutputStream out = response.getOutputStream()) {
                    ExcelWriter emptyWriter = ExcelUtil.getWriter(true);
                    emptyWriter.writeHeadRow(Arrays.asList("无数据"));
                    emptyWriter.flush(out);
                    emptyWriter.close();
                }
                return;
            }

            // 创建Excel写入器
            ExcelWriter writer = ExcelUtil.getWriter(true);

            // 自定义标题
            writer.addHeaderAlias("cno", "客户编号");
            writer.addHeaderAlias("cname", "客户姓名");
            writer.addHeaderAlias("gender", "性别");
            writer.addHeaderAlias("age", "年龄");
            writer.addHeaderAlias("phone", "手机号码");
            writer.addHeaderAlias("address", "居住地址");

            // 写入数据
            writer.write(all, true);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("客户数据", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            // 输出到响应流
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (Exception e) {
            log.error("导出失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"code\":\"-1\",\"msg\":\"导出失败: " + e.getMessage() + "\"}");
        }
    }

    // 导入Excel
    @PostMapping("/import")
    public Result importCustomer(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件");
        }

        try (InputStream inputStream = file.getInputStream()) {
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            // 设置列别名映射
            reader.addHeaderAlias("客户编号", "cno");
            reader.addHeaderAlias("客户姓名", "cname");
            reader.addHeaderAlias("性别", "gender");
            reader.addHeaderAlias("年龄", "age");
            reader.addHeaderAlias("手机号码", "phone");
            reader.addHeaderAlias("居住地址", "address");

            // 读取为Customer列表
            List<Customer> list = reader.readAll(Customer.class);

            if (CollectionUtil.isEmpty(list)) {
                return Result.error("Excel中没有有效数据");
            }

            int successCount = 0;
            int errorCount = 0;
            StringBuilder errors = new StringBuilder();

            for (Customer customer : list) {
                try {
                    // 基本数据校验
                    if (StrUtil.isBlank(customer.getCname())) {
                        throw new MyOwnException("客户姓名不能为空");
                    }
                    if (StrUtil.isBlank(customer.getPhone())) {
                        throw new MyOwnException("手机号码不能为空");
                    }

                    // 检查手机号是否已存在
                    Customer existCustomer = customerMapper.selectByPhone(customer.getPhone());
                    if (existCustomer != null) {
                        throw new MyOwnException("手机号已存在");
                    }

                    // 插入数据库
                    customerMapper.insert(customer);
                    successCount++;
                } catch (Exception e) {
                    errorCount++;
                    errors.append("行").append(list.indexOf(customer) + 1)
                            .append(": ").append(e.getMessage()).append("; ");
                }
            }

            String msg = String.format("导入完成! 成功: %d 条, 失败: %d 条", successCount, errorCount);
            if (errorCount > 0) {
                msg += "。失败原因: " + errors.toString();
            }

            return Result.success(msg);
        } catch (Exception e) {
            log.error("导入失败", e);
            return Result.error("导入失败: " + e.getMessage());
        }
    }
}
